window.addEventListener('DOMContentLoaded',async()=>{
    //要将地址栏上的id获取到
    let id=window.location.search.split("=")[1];
    const {code,message,data:{tid,tname,age,lession}}=await fetchTeacherByIdApi(id)
    if(code){
        document.querySelector("#tid").value=tid
        document.querySelector("#tname").value=tname;
        document.querySelector("#age").value=age;
        document.querySelector("#lession").value=lession
    }
    document.querySelector('#upateBtn').addEventListener('click',async()=>{
        let tid=document.querySelector("#tid").value
        let tname=document.querySelector("#tname").value
        let age=document.querySelector("#age").value
        let lession=document.querySelector("#lession").value
        let teacher={tid,tname,age,lession}
        const {code,message}=await updateTeacherApi(teacher)
        if(code){
            alert(message)
            window.location="index.html"
        }
    })
})

const updateTeacherApi=({tid,tname,age,lession})=>{
    return new Promise((resolve,reject)=>{
        const xhr=new XMLHttpRequest()
        xhr.open('PUT','/teachers/modify',true)
        xhr.setRequestHeader('Content-Type',"application/x-www-form-urlencoded")
        //设置发送
        xhr.send(`tid=${tid}&tname=${tname}&age=${age}&lession=${lession}`)
        xhr.onreadystatechange=()=>{
            if(xhr.readyState==4){
                if(xhr.status==200){
                    resolve(JSON.parse(xhr.responseText))
                }
            }
        }
    })
}

const fetchTeacherByIdApi=id=>{
    return new Promise((resolve,reject)=>{
        const xhr=new XMLHttpRequest()
        xhr.open("GET",`/teachers/byid/${id}`,true)
        xhr.send()
        xhr.onreadystatechange=()=>{
            if(xhr.readyState==4){
                if(xhr.status==200){
                    resolve(JSON.parse(xhr.responseText))
                }
            }
        }
    })
}